//
//  AddressManageViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/4.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "AddressManageViewController.h"
#import "AddressModel.h"
#import "AddressManageTableViewCell.h"
#import "AddressEditViewController.h"

@interface AddressManageViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    UIButton *_tempButton;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (nonatomic, strong) NSMutableArray *tableArray;
@property (nonatomic, assign) NSInteger page;

@end

@implementation AddressManageViewController
#pragma mark - Get
- (NSMutableArray *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - IBAction
- (IBAction)addAddressButtonAction:(id)sender {
    AddressEditViewController *editVC = [[AddressEditViewController alloc] init];
    if (self.isShopcartNew) {
        editVC.type = AddressTypeShopcartNew;
    } else {
        editVC.type = AddressTypeNew;
    }
    [self.navigationController pushViewController:editVC animated:YES];
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"地址管理";
    [self hiddenShadowImage:NO];
    
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    //[self.sureButton setGradientHorizontal:nil];
}
#pragma mark - action
static NSString *addressManageIdentifier = @"addressManageIdentifier";
- (void)createTableView {
    self.page = 1;
    
    [self.tableView clearExtendCellLine];
    [self.tableView registerNib:[UINib nibWithNibName:@"AddressManageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:addressManageIdentifier];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self getNetData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getNetData];
    }];
    [self.tableView.mj_footer setHidden:YES];
}

- (void)defaultButtonAction:(NSInteger)index {
    // 调用修改默认的接口，之后刷界面
    AddressModel *model = self.tableArray[index];
    [self defaultAddress:model.daid];
}
- (void)editButtonAction:(NSInteger)index {
    AddressEditViewController *editVC = [[AddressEditViewController alloc] init];
    editVC.type = AddressTypeEdit;
    editVC.editModel = self.tableArray[index];
    [self.navigationController pushViewController:editVC animated:YES];
}
- (void)deleteButtonAction:(NSIndexPath *)indexPath {
    // 删除的接口，成功后动画
    [self showAlertWithTitleArray:@[@"取消",@"删除"] title:@"提示" message:@"是否确认删除该地址?" alertStyle:UIAlertControllerStyleAlert];
    __block typeof(self) blockSelf = self;
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"删除"]) {
            AddressModel *model = blockSelf.tableArray[indexPath.row];
            [blockSelf deleteAddress:model.daid indexPath:indexPath];
        }
    };
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    if (self.page != 1) {
        _page--;
    }
}

#pragma mark - 网络请求
- (void)defaultAddress:(NSString *)daid {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Default_Address parameters:@{@"daid":daid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self getNetData];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)deleteAddress:(NSString *)daid indexPath:(NSIndexPath *)indexPath {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Delete_Address parameters:@{@"daid":daid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            
            AddressModel *model = self.tableArray[indexPath.row];
            [self.tableArray removeObjectAtIndex:indexPath.row];
            
            if ([[UserInfo shareInstance].user.defaultAddress.daid isEqualToString:model.daid]) {
                [UserInfo shareInstance].user.defaultAddress = nil;
                if (self.tableArray.count > 0) {
                    [UserInfo shareInstance].user.defaultAddress = [self.tableArray firstObject];
                }
                [[UserInfo shareInstance] updateUserModel];
            }
            
            // 适配iOS11
            if (@available(iOS 11.0, *)) {
                [self.tableView performBatchUpdates:^{
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                } completion:^(BOOL finished) {
                    [self.tableView reloadData];
                }];
            } else {
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                [self.tableView endUpdates];
            }
            
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getNetData {
    
    [MYAFNetworking POST:URL_Get_Address parameters:@{@"pageSize":PageSize,@"pageNumber":@(self.page)} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self endRefresh];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
            if ([dics[@"totalRow"] integerValue] > self.tableArray.count) {
                [self.tableView.mj_footer setHidden:NO];
            } else {
                [self.tableView.mj_footer setHidden:YES];
            }
            
            if (_page == 1) {
                [self.tableArray removeAllObjects];
                [self.tableView.mj_footer resetNoMoreData];
            }
            // 数据列表
            NSArray *arr = dics[@"data"][@"list"];
            if (arr.count == 0 && _page != 1) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                [self getNetFailure];
                return;
            }
            for (NSDictionary *dataDic in arr) {
                AddressModel *model = [AddressModel mj_objectWithKeyValues:dataDic];
                [self.tableArray addObject:model];
                
                if (model.isdefault) {
                    [UserInfo shareInstance].user.defaultAddress = model;
                    [[UserInfo shareInstance] updateUserModel];
                }
                if ([model isEqual:[arr lastObject]] && ![UserInfo shareInstance].user.defaultAddress) {
                    [UserInfo shareInstance].user.defaultAddress = [arr firstObject];
                    [[UserInfo shareInstance] updateUserModel];
                }
            }
            [self.tableView reloadData];
            
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            [self getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [self getNetFailure];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressManageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:addressManageIdentifier forIndexPath:indexPath];
    AddressModel *model = self.tableArray[indexPath.row];
    [cell.nameLabel setText:model.daname];
    [cell.phoneLabel setText:[LXLIsPhoneNumber phoneNumber:model.datel]];
    [cell.addressLabel setText:[NSString stringWithFormat:@"%@ %@ %@ %@",model.pname,model.cname,model.aname,model.daaddress]];
    [cell.defaultButton setSelected:model.isdefault];
    if (model.isdefault) {
        _tempButton = cell.defaultButton;
    }
    
    [cell.defaultButton setTag:ButtonBaseTagDefault+indexPath.row];
    [cell.editButton setTag:ButtonBaseTagEdit+indexPath.row];
    [cell.deleteButton setTag:ButtonBaseTagDelete+indexPath.row];
    
    cell.block = ^(NSInteger tag, AddressClickType type) {
        switch (type) {
            case AddressClickTypeDefault:
            {
                [_tempButton setSelected:NO];
                _tempButton = cell.defaultButton;
                [_tempButton setSelected:YES];
                [self defaultButtonAction:tag-ButtonBaseTagDefault];
                break;
            }
            case AddressClickTypeEdit:
            {
                [self editButtonAction:tag-ButtonBaseTagEdit];
                break;
            }
            case AddressClickTypeDelete:
            {
                [self deleteButtonAction:indexPath];
                break;
            }
            default:
                break;
        }
    };
    
    return cell;
}
#pragma mark - UITableViewDelegate


#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无地址"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    _page = 1;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
